package com.hww.test_p;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author hww
 * @date 2022/5/18/0018
 * email: heww@zhongyuntech.cn
 * description:
 */
public class IOShell {

    private Process process = null;

    private InputStream inputStream = null;
    private OutputStream outputStream = null;

    private DataInputStream dataInputStream = null;
    private DataOutputStream dataOutputStream = null;

    public IOShell() {
        init();
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void init() {
        try {
            if (null == process) {
                process = Runtime.getRuntime().exec("sh");
                outputStream = process.getOutputStream();
                inputStream = process.getInputStream();

                dataInputStream = new DataInputStream(inputStream);
                dataOutputStream = new DataOutputStream(outputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void shellCMD(String cmd) {
        try {
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getOutPutString(){
        try {
            return dataInputStream.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public void close() {
        try {
            dataOutputStream.close();
        } catch (Exception e) {
            e.getMessage();
        }
        try {
            dataInputStream.close();
        } catch (Exception e) {
            e.getMessage();
        }
        try {
            outputStream.close();
        } catch (Exception e) {
            e.getMessage();
        }
        try {
            inputStream.close();
        } catch (Exception e) {
            e.getMessage();
        }
        try {
            process.destroy();
        } catch (Exception e) {
            e.getMessage();
        }
    }

}
